package com.zuipin.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zuipin.entity.OrderDetail;
import com.zuipin.entity.OrderInfo;
import com.zuipin.entity.OrderInfoLog;
import com.zuipin.entity.PayOrder;
import com.zuipin.entity.SysUser;
import com.zuipin.entity.product.ProductInfo;
import com.zuipin.enums.OrderStatusEnum;
import com.zuipin.enums.PremiumEnum;
import com.zuipin.framework.emuns.ErrorCode;
import com.zuipin.framework.exception.CustomException;
import com.zuipin.framework.result.Result;
import com.zuipin.mapper.OrderConsigneeMapper;
import com.zuipin.mapper.OrderDetailMapper;
import com.zuipin.mapper.OrderInfoLogMapper;
import com.zuipin.mapper.OrderInfoMapper;
import com.zuipin.mapper.PayOrderMapper;
import com.zuipin.service.IOrderDetailService;
import com.zuipin.service.IPayOrderService;
import com.zuipin.service.IProductInfoService;
import com.zuipin.service.ISysUserService;
import com.zuipin.util.CommonUtils;
import com.zuipin.util.DateUtils;
import com.zuipin.util.StringUtil;
import com.zuipin.vo.OrderDetailVo;

@Service
public class OrderDetailServiceImpl implements IOrderDetailService {
	@Resource
	private OrderInfoMapper			orderInfoMap;
	@Resource
	private OrderConsigneeMapper	orderConsigneeMapper;
	protected final Logger			log	= Logger.getLogger(getClass());
	@Resource
	private OrderInfoLogMapper		orderInfoLogMapper;
	@Resource
	private OrderDetailMapper		orderDetailMapper;
	
	@Resource
	private PayOrderMapper			payOrderMapper;
	
	@Resource
	private IPayOrderService		payOrderService;
	
	@Resource
	private ISysUserService			sysUserService;
	@Resource
	private IProductInfoService		productInfoService;
	
	/**
	 * 
	* @Description:添加商品详情
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月13日上午9:45:14
	 */
	public List<OrderDetail> addOrderDetail(OrderInfo orderInfo, Long createId,
			List<OrderDetailVo> orderDetailVo) {
		List<OrderDetail> details = new ArrayList<OrderDetail>();
		for (OrderDetailVo vo : orderDetailVo) {
			OrderDetail od = new OrderDetail();
			od.setOrderId(orderInfo.getId());
			od.setCreateId(createId);
			od.setCreateTime(DateUtils.getCurrentDateTime());
			od.setPremiumEnum(vo.getPremiums());
			od.setJfPrice(vo.getJfPrice());
			od.setDelFlag(PayOrder.NO);
			od.setUpdateTime(DateUtils.getCurrentDateTime());
			od.setPackNo(vo.getPackNo());
			od.setProductName(vo.getProductName());
			od.setProductNum(vo.getProductNum());
			od.setProSku(vo.getProSku());
			od.setPurchasePrice(vo.getPurchasePrice());
			od.setProductProperty(vo.getProductProperty());
			od.setProductPrice(vo.getProductPrice());
			od.setPackWeight(vo.getPackWeight());
			od.setSubtotal(vo.getSubtotal());
			od.setSupplierId(vo.getSupplierId());
			od.setUseCashBackSum(vo.getUseCashBackSum());
			od.setUseJfSum(vo.getUseJfSum());
			od.setGiveJfSum(vo.getGiveJfSum());
			od.setGiveCashBackSum(vo.getGiveCashBackSum());
			od.setBusinessType(vo.getBusinessType());
			orderDetailMapper.insertSelective(od);
			details.add(od);
		}
		return details;
	}
	
	/**
	 * 
	* @Description:真删
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月13日上午11:20:23
	 */
	public void delOrderDetail(Long id) {
		orderDetailMapper.deleteByPrimaryKey(id);
	}
	
	/**
	 * 
	* @Description:假删
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月13日上午11:20:23
	 */
	public void deleteOrderDetail(Long id) {
		orderDetailMapper.deleteOrderDetail(id);
	}
	
	/**
	 * 
	* @Description:
	* @Title: 
	* @author: xujinding
	* @date: 2017年4月13日上午11:20:23
	 */
	public OrderDetail findOrderDetailById(Long id) {
		return orderDetailMapper.selectByPrimaryKey(id);
	}
	
	/**
	 * 
	* @Description:新增赠品
	* @Title: 
	* @author: xujinding
	 * @throws CustomException 
	* @date: 2017年4月13日上午10:00:59
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result addPremiums(String orderNo, Long sysUserId, OrderDetailVo orderDetailVo)
			throws CustomException {
		Result res = new Result();
		if (orderDetailVo != null && !StringUtil.isBlank(orderNo)) {
			OrderInfo orderInfo = orderInfoMap.findOrderInfoByOrderNo(orderNo);
			if (orderInfo != null) {
				if (OrderStatusEnum.支付成功待审核.getValue().equals(orderInfo.getOrderStatus())
						|| OrderStatusEnum.待审核.getValue().equals(orderInfo.getOrderStatus())
						|| OrderStatusEnum.待付款.getValue().equals(orderInfo.getOrderStatus())) {
					List<OrderDetailVo> list = new ArrayList<OrderDetailVo>();
					ProductInfo pro = productInfoService.selectByProSku(orderDetailVo.getProSku());
					orderDetailVo.setBusinessType(pro.getBusinessType());
					orderDetailVo.setProductName(pro.getProName());
					orderDetailVo.setGiveJfSum(0);
					orderDetailVo.setPremiums(PremiumEnum.NEW_ADD_PREMIUM + "");
					orderDetailVo.setJfPrice(0);
					orderDetailVo.setPurchasePrice(new BigDecimal(0));
					orderDetailVo.setProductPrice(new BigDecimal(0));
					orderDetailVo.setSubtotal(new BigDecimal(0));
					orderDetailVo.setSupplierId(111111100L);
					orderDetailVo.setUseCashBackSum(new BigDecimal(0));
					orderDetailVo.setUseJfSum(0);
					orderDetailVo.setGiveJfSum(0);
					orderDetailVo.setGiveCashBackSum(new BigDecimal(0));
					list.add(orderDetailVo);
					List<OrderDetail> details = addOrderDetail(orderInfo, sysUserId, list);
					if (details != null && details.size() > 0) {
						OrderInfoLog orderInfoLog = new OrderInfoLog();
						orderInfoLog.setCreateTime(DateUtils.getCurrentDateTime());
						// orderInfoLog.setIpAddress(ip);
						orderInfoLog.setSysUserId(sysUserId);
						orderInfoLog.setUpdateInfo("新增了商品编码为" + orderDetailVo.getProSku() + "，数量为："
								+ orderDetailVo.getProductNum() + "的赠品");
						orderInfoLog.setOrderNo(orderInfo.getOrderNo());
						orderInfoLogMapper.insertSelective(orderInfoLog);
						SysUser sysUser = sysUserService.findById(sysUserId);
						if (sysUser == null) {
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查询不到操作人员");
						}
						boolean isHoldSuccess = payOrderService.preholdCisStock(details,
								PayOrder.PRE_HOLD_STOCK, orderInfo, "新增赠品预占虚拟库存",
								sysUser.getRealName() + "", null);
						if (!isHoldSuccess) {
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(),
									"预占库存失败，请检查商品在库存系统中是否存在");
						}
						res.setErrorCode(ErrorCode.SUCCESS);
						res.setData(details.get(0));
					} else {
						res.setErrorCode(ErrorCode.ORDER_ERRPR);
						res.setMessage("新增赠品失败");
					}
				} else {
					res.setErrorCode(ErrorCode.ORDER_ERRPR);
					res.setMessage("只有待审核，或支付成功待审核，或待付款才能新增赠品");
				}
				
			} else {
				//没有该订单
				res.setErrorCode(ErrorCode.ORDER_ERRPR);
				res.setMessage("查无订单");
			}
		} else {
			//参数有误
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("参数有误");
		}
		return res;
	}
	
	/**
	 * 删除赠品--真删
	 * @throws CustomException 
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Result delPremiums(String orderDetailIds, Long sysUserId) throws CustomException {
		Result res = new Result();
		if (StringUtil.isNotBlank(orderDetailIds)) {
			String[] ids = CommonUtils.splitBySymbol(orderDetailIds, ",");
			for (String id : ids) {
				OrderDetail od = findOrderDetailById(Long.valueOf(id));
				if (od != null && (PremiumEnum.NEW_ADD_PREMIUM + "").equals(od.getPremiumEnum())) {
					OrderInfo order = orderInfoMap.selectByPrimaryKey(od.getOrderId());
					if (OrderStatusEnum.支付成功待审核.getValue().equals(order.getOrderStatus())
							|| OrderStatusEnum.待审核.getValue().equals(order.getOrderStatus())
							|| OrderStatusEnum.待付款.getValue().equals(order.getOrderStatus())) {
						deleteOrderDetail(Long.valueOf(id));
						OrderInfoLog orderInfoLog = new OrderInfoLog();
						orderInfoLog.setCreateTime(DateUtils.getCurrentDateTime());
						orderInfoLog.setSysUserId(sysUserId);
						orderInfoLog.setUpdateInfo(
								"删除了商品编码为" + od.getProSku() + "，数量为：" + od.getProductNum() + "的赠品");
						orderInfoLog.setOrderNo(order.getOrderNo());
						orderInfoLogMapper.insertSelective(orderInfoLog);
						//虚拟预占
						List<OrderDetail> list = new ArrayList<OrderDetail>();
						list.add(od);
						SysUser sysUser = sysUserService.findById(sysUserId);
						if (sysUser == null) {
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(), "查询不到操作人员");
						}
						boolean isHoldSuccess = this.payOrderService.preholdCisStock(list,
								PayOrder.PRE_RELEASE_STOCK, order, "删除赠品预占虚拟库存",
								sysUser.getRealName() + "", PayOrder.NO);
						if (!isHoldSuccess) {
							throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(),
									"预占库存失败，请检查商品在库存系统中是否存在");
						}
						res.setErrorCode(ErrorCode.SUCCESS);
					} else {
						res.setErrorCode(ErrorCode.ORDER_ERRPR);
						res.setMessage("订单不存在或订单已经审核了");
					}
					
				} else {
					throw new CustomException(ErrorCode.ORDER_ERRPR.getCode(),
							"包含商品不存在或不是后台新增的赠品：：" + id);
				}
			}
		} else {
			res.setErrorCode(ErrorCode.ORDER_ERRPR);
			res.setMessage("参数有误");
		}
		return res;
	}
	
	/**
	 * 查询确认收货 未评价的订单  注意天数
	 * @param day
	 * @return
	 */
	public List<Map<String, Object>> quartzCommentProduct(Integer day, Long sysId) {
		return orderDetailMapper.quartzCommentProduct(day, sysId);
	}
}
